package com.haojii.jdo.basic;
import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.haojii.jdo.utils.PMF;

@SuppressWarnings("serial")
public class UserKeyKeyTestServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		System.out.println("1.0 Create and persist UserLong with @PrimaryKey: Key");
		UserKey user = new UserKey("name1",UserKey.class.getSimpleName());
		pm.makePersistent(user);
		
		System.out.println("1.1 Query UserKey with getObjectById");
	    UserKey tmpUser = null;
	    Key key = user.getKey();
	    
	    tmpUser = pm.getObjectById(UserKey.class, key);
	    System.out.println("(1)user==tmpUser ? "+(user==tmpUser));
	    
	    Key createdKey = KeyFactory.createKey(UserKey.class.getSimpleName(), user.getName());
	    tmpUser = pm.getObjectById(UserKey.class, createdKey);
	    System.out.println("(2)user==tmpUser ? "+(user==tmpUser));
	    
	    System.out.println("1.2 Query UserKey with name1");
	    tmpUser = null;
	    Query query = pm.newQuery(UserKey.class); 
	    query.setFilter("name == nameParam"); 
	    query.setOrdering("date desc"); 
	    query.declareParameters("String nameParam");
	    try { 
	        List<UserKey> results = (List<UserKey>) query.execute("name1"); 
	        System.out.println("All UserKey size:"+results.size());
	        if (results.iterator().hasNext()) { 
	            for (UserKey e : results) { 
	            	tmpUser = e;
	                System.out.println(" "+e);
	            } 
	        } else { 
	        	System.out.println("1.2 Query get empty result");
	        } 
	    } finally { 
	        query.closeAll(); 
	    }
	    
	    if (tmpUser != null)
	    {
	    	System.out.println("1.3 Update the searched result[0] UserKey with name1->NAME!");
	    	System.out.println("user==tmpUser?"+(user==tmpUser));
	    	tmpUser.setName("NAME!");
	    	pm.makePersistent(tmpUser);
	    }
	    
	    System.out.println("1.4 Delete UserKey with name1");
	    System.out.println(" ->"+user);
	    pm.deletePersistent(user);

	    
	    query = pm.newQuery(UserKey.class); 
	    System.out.println("All UserKey size:"+((List<UserKey>) query.execute()).size());
		resp.getWriter().println("Hello, world");
	}
}
